﻿using DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace ProductShop
{
    class PresenterLogin : IPresenterLogin
    {
        private readonly ILoginView view;
        public IUnitOfWork unitOfWork { get; private set; }

        public event Action LoginAccepted;
        public event Action RegistrationAccepted;

        public PresenterLogin(ILoginView view, IUnitOfWork unitOfWork)
        {
            this.view = view;
            view.LoginRequested += OnLoginRequested;
            view.RegistrationRequested += OnRegistrationRequested;

            this.unitOfWork = unitOfWork;
        }

        private void Invoke(Action action)
        {
            if (action != null)
            {
                action();
            }
        }

        private void OnRegistrationRequested()
        {
            if (unitOfWork.Users.FindByEmail(view.RegistrationEmail) != null)
                return;

            User user = new User();
            user.FirstName = view.UserFirstName;
            user.LastName = view.UserLastName;
            user.Email = view.RegistrationEmail;
            user.Password = GetPasswordHash(view.RegistrationPassword);
            Invoke(RegistrationAccepted);
        }

        private void OnLoginRequested()
        {
            User loginingUser = unitOfWork.Users.FindByEmail(view.LoginEmail);
            if (loginingUser.Password != GetPasswordHash(view.LoginPassword))
                return;
            Invoke(LoginAccepted);
        }

        private Byte[] GetPasswordHash(String password)
        {
            SHA512 alg = SHA512.Create();
            return alg.ComputeHash(Encoding.UTF8.GetBytes(password + "$#"));
        }

        public void ShowLoginView()
        {
            view.ShowForm();
        }

        public void CloseLoginView()
        {
            view.CloseForm();
        }
    }
}
